document.addEventListener('DOMContentLoaded', function() {
    // 获取URL参数
    const urlParams = new URLSearchParams(window.location.search);
    const email = urlParams.get('email');
    const token = urlParams.get('token');
    
    // 验证重置令牌
    if (!email || !token || !validateResetToken(email, token)) {
        alert('无效的重置链接或链接已过期');
        window.location.href = 'forgot-password.html';
        return;
    }
    
    // 设置隐藏字段
    document.getElementById('resetEmail').value = email;
    document.getElementById('resetToken').value = token;
    
    // 表单元素
    const resetForm = document.getElementById('resetForm');
    const newPasswordInput = document.getElementById('newPassword');
    const confirmNewPasswordInput = document.getElementById('confirmNewPassword');
    const newPasswordError = document.getElementById('newPasswordError');
    const confirmPasswordError = document.getElementById('confirmPasswordError');
    const toggleNewPassword = document.getElementById('toggleNewPassword');
    const toggleConfirmNewPassword = document.getElementById('toggleConfirmNewPassword');
    
    // 显示/隐藏密码
    toggleNewPassword.addEventListener('click', function() {
        togglePasswordVisibility(newPasswordInput, this);
    });
    
    toggleConfirmNewPassword.addEventListener('click', function() {
        togglePasswordVisibility(confirmNewPasswordInput, this);
    });
    
    // 密码强度检测
    newPasswordInput.addEventListener('input', function() {
        validatePassword();
        checkPasswordStrength();
    });
    
    // 确认密码验证
    confirmNewPasswordInput.addEventListener('input', function() {
        validateConfirmPassword();
    });
    
    // 表单提交
    resetForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        const isPasswordValid = validatePassword();
        const isConfirmPasswordValid = validateConfirmPassword();
        
        if (isPasswordValid && isConfirmPasswordValid) {
            resetPassword();
        }
    });
    
    // 验证重置令牌
    function validateResetToken(email, token) {
        const resetData = JSON.parse(localStorage.getItem('resetToken'));
        
        if (!resetData || 
            resetData.email !== email || 
            resetData.token !== token || 
            resetData.expires < Date.now()) {
            return false;
        }
        
        return true;
    }
    
    // 重置密码
    function resetPassword() {
        const resetBtn = document.querySelector('.btn-reset');
        const originalText = resetBtn.innerHTML;
        resetBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 处理中...';
        resetBtn.disabled = true;
        
        const email = document.getElementById('resetEmail').value;
        const newPassword = newPasswordInput.value;
        
        // 更新用户密码
        let users = JSON.parse(localStorage.getItem('users')) || [];
        const userIndex = users.findIndex(user => user.email === email);
        
        if (userIndex !== -1) {
            users[userIndex].password = newPassword; // 注意：实际应用中应该加密
            localStorage.setItem('users', JSON.stringify(users));
            
            // 清除重置令牌
            localStorage.removeItem('resetToken');
            
            setTimeout(() => {
                alert('密码重置成功！请使用新密码登录');
                window.location.href = 'login.html';
            }, 1000);
        } else {
            alert('用户不存在');
            resetBtn.innerHTML = originalText;
            resetBtn.disabled = false;
        }
    }
    
    // 密码验证
    function validatePassword() {
        const password = newPasswordInput.value;
        
        if (password === '') {
            showError(newPasswordError, '请输入新密码');
            return false;
        } else if (password.length < 8) {
            showError(newPasswordError, '密码长度不能少于8位');
            return false;
        } else {
            hideError(newPasswordError);
            return true;
        }
    }
    
    // 确认密码验证
    function validateConfirmPassword() {
        const password = newPasswordInput.value;
        const confirmPassword = confirmNewPasswordInput.value;
        
        if (confirmPassword === '') {
            showError(confirmPasswordError, '请再次输入密码');
            return false;
        } else if (password !== confirmPassword) {
            showError(confirmPasswordError, '两次输入的密码不一致');
            return false;
        } else {
            hideError(confirmPasswordError);
            return true;
        }
    }
    
    // 密码强度检测
    function checkPasswordStrength() {
        const password = newPasswordInput.value;
        let strength = 0;
        
        if (password.length >= 8) strength += 1;
        if (password.length >= 12) strength += 1;
        if (/[a-z]/.test(password)) strength += 1;
        if (/[A-Z]/.test(password)) strength += 1;
        if (/\d/.test(password)) strength += 1;
        if (/[^a-zA-Z0-9]/.test(password)) strength += 1;
        
        const strengthPercent = (strength / 6) * 100;
        const strengthBar = document.getElementById('strengthBar');
        const strengthText = document.getElementById('strengthText');
        
        strengthBar.style.setProperty('--strength-width', `${strengthPercent}%`);
        
        if (strength <= 2) {
            strengthBar.style.setProperty('--strength-color', '#ff4757');
            strengthText.textContent = '密码强度: 弱';
        } else if (strength <= 4) {
            strengthBar.style.setProperty('--strength-color', '#ffa502');
            strengthText.textContent = '密码强度: 中等';
        } else {
            strengthBar.style.setProperty('--strength-color', '#2ed573');
            strengthText.textContent = '密码强度: 强';
        }
    }
    
    // 切换密码可见性
    function togglePasswordVisibility(input, button) {
        const type = input.getAttribute('type') === 'password' ? 'text' : 'password';
        input.setAttribute('type', type);
        button.innerHTML = type === 'password' ? '<i class="fas fa-eye"></i>' : '<i class="fas fa-eye-slash"></i>';
    }
    
    // 显示错误信息
    function showError(element, message) {
        element.textContent = message;
        element.style.display = 'block';
    }
    
    // 隐藏错误信息
    function hideError(element) {
        element.textContent = '';
        element.style.display = 'none';
    }
});